import {defineStore} from 'pinia';
import {SseEmitterHandler} from "@/utils/sse/types.ts";
import {store} from "@/stores/index.ts";

const MsgSubscribe: string = `http://localhost:8005/msg/sse/subscribe`
const MsgUnSubscribe: string = `http://localhost:8005/msg/sse/unsubscribe`
export const useSubscribeDataStore = defineStore({
    id: 'subscribeData',
    state: (): {} => ({
        sseEmitterHandler: SseEmitterHandler,

    }),
    getters:{
        getSseEmitterHandler(state) {
            return state.sseEmitterHandler
        },
    },
    actions: {
        set_sseEmitterHandler(sseEmitterHandler) {
            this.sseEmitterHandler = sseEmitterHandler
        },
        initSubscribe() {
            return new Promise((resolve, reject) => {
                const subscribeUrl: string = MsgSubscribe
                const unSubscribeUrl: string = MsgUnSubscribe
                console.log('', subscribeUrl, unSubscribeUrl)
                const sseEmitterHandler = SseEmitterHandler.of(subscribeUrl, unSubscribeUrl).create();
                if (!sseEmitterHandler) {
                    console.log('sseEmitterHandler fail', sseEmitterHandler)
                    return
                }
                this.set_sseEmitterHandler(sseEmitterHandler)

                sseEmitterHandler.registerOpenListener((event) => {
                    console.log('onopen event', event)
                })
                sseEmitterHandler.registerErrorListener((event) => {
                    console.log('onerror event', event)
                })
                sseEmitterHandler.registerMessageListener((event) => {
                    console.log('onmessage event', event)
                })
                sseEmitterHandler.subscribeHandle('subscribe', (event) => {
                    console.log('subscribe event', event)
                    const result = JSON.parse(event.data);
                    console.log('subscribe', result)
                    const {type, topic, key} = result
                    if (topic) {
                        sseEmitterHandler.addTopic(topic)
                    }
                })
                resolve(sseEmitterHandler)
            })
        }
    }
});

export function useSubscribeDataStoreWithOut() {
    return useSubscribeDataStore(store);
}
